package com.wyq.miaosha.service;

import com.wyq.miaosha.domain.MiaoshaOrder;
import com.wyq.miaosha.domain.MiaoshaUser;
import com.wyq.miaosha.domain.OrderInfo;
import com.wyq.miaosha.exception.GlobalException;
import com.wyq.miaosha.redis.MiaoshaKey;
import com.wyq.miaosha.redis.RedisService;
import com.wyq.miaosha.result.CodeMsg;
import com.wyq.miaosha.util.MD5Util;
import com.wyq.miaosha.util.UUIDUtil;
import com.wyq.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MiaoshaService {

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;
    @Autowired
    RedisService redisService;

    public String createMiaoshaPath(MiaoshaUser user, long goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisService.set(MiaoshaKey.getMiaoshaPath,""+user.getId()+""+goodsId,str);
        return str;
    }

    @Transactional
    public OrderInfo miaosha(MiaoshaUser user, GoodsVo goods) {
        //减库存
        if(goodsService.reduceStock(goods) > 0){
            //下订单 写入秒杀订单
            return orderService.createOrder(user, goods);
        }else {
            setGoodsOver(goods.getId());
            throw new GlobalException(CodeMsg.MIAO_SHA_OVER);
        }
    }

    //获取秒杀结果
    public long getMiaoshaResult(Long userId, long goodsId) {
        MiaoshaOrder mo = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        if(mo != null){
            return mo.getOrderId();
        }else {
            boolean isOver = getGoodsOver(goodsId);
            if (isOver){
                return -1;
            }else {
                return 0;
            }
        }
    }

    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(MiaoshaKey.isGoodsOver, "" + goodsId);

    }
    private void setGoodsOver(Long goodsId) {
        redisService.set(MiaoshaKey.isGoodsOver,""+goodsId,true);
    }

    public boolean checkPath(MiaoshaUser user, long goodsId, String path) {
        if(user == null || path == null){
            return false;
        }
        return path.equals(redisService
                .get(MiaoshaKey.getMiaoshaPath,""+user.getId()+""+goodsId,String.class));
    }
}
